package ca.ubc.icapture.genapha.actions;

import ca.ubc.icapture.genapha.beans.SNPInfo;
import ca.ubc.icapture.genapha.forms.GenerateAnalysisFileForm;
import ca.ubc.icapture.genapha.forms.SnpListForm;
import icapture.SQLMgr;
import icapture.beans.Format;
import icapture.beans.DB.Phenotypes;
import icapture.beans.DB.Cohort;
import icapture.beans.DB.SNP;
import icapture.genapha.GenotypeToolsManager;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * Created by IntelliJ IDEA.
 * User: btripp
 * Date: Sep 19, 2006
 * Time: 1:36:05 PM
 * To change this template use File | Settings | File Templates.
 */
public class GenerateAnalysisFileAction extends Action {

   /**
	* Constructor
	*/
	public GenerateAnalysisFileAction() {
		super();
	}

    public ActionForward execute(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response)
		throws Exception {

        ActionForward forward = new ActionForward();
        //HttpSession session = request.getSession();
        GenerateAnalysisFileForm generateAnalysisFileForm = (GenerateAnalysisFileForm) form;

        if(generateAnalysisFileForm.getAction().equalsIgnoreCase("Display")){
            SnpListForm snpListForm = (SnpListForm)request.getAttribute("snpListForm");
            if(snpListForm!=null){
                StringBuffer snps = new StringBuffer();
                ArrayList<SNPInfo> snpList = snpListForm.getSnpList();
                Iterator<SNPInfo> iter = snpList.iterator();
                while(iter.hasNext()){
                    SNP snp = iter.next().getSnp();
                    snps.append(snp.getRsNumber() + "\n");
                }
                generateAnalysisFileForm.setSnpList(snps.toString());
            }
            //fill phenotype list
            ArrayList<Phenotypes> phenList = SQLMgr.getPhenotypes();
            ArrayList<LabelValueBean> list = new ArrayList<LabelValueBean>();

            Iterator<Phenotypes> iter = phenList.iterator();
            while(iter.hasNext()){
                Phenotypes phen = iter.next();
                list.add(new LabelValueBean(phen.getName(),Integer.toString(phen.getPhenotypeID())));
            }
            generateAnalysisFileForm.setPhenotypeList(list);


            //fill cohort list
            ArrayList<Cohort> cohortList = SQLMgr.getCohorts();
            list = new ArrayList<LabelValueBean>();

            Iterator<Cohort> iter2 = cohortList.iterator();
            while(iter2.hasNext()){
                Cohort cohort = iter2.next();
                list.add(new LabelValueBean(cohort.getName(),Integer.toString(cohort.getCohortID())));
            }
            generateAnalysisFileForm.setCohortList(list);

            list = new ArrayList<LabelValueBean>();
            GenotypeToolsManager gtm = new GenotypeToolsManager();
            Format[] formats = gtm.getFormats();
            for(int i =0;i<formats.length;i++){
                list.add(new LabelValueBean(formats[i].getName(),Integer.toString(i)));
            }
            generateAnalysisFileForm.setFormatList(list);

            forward = mapping.findForward("display");
        }else if(generateAnalysisFileForm.getAction().equalsIgnoreCase("Generate")){
            try {
                String[] snps = generateAnalysisFileForm.getSnpList().split("[,\n]");
                for(int i=0;i<snps.length;i++){
                    snps[i] = snps[i].trim();
                }
                //parse list of snp's

                //todo maybe check that they exist

                //return error if snplist is not formated correctly

                // set the http content type to "APPLICATION/OCTET-STREAM
                response.setContentType("APPLICATION/OCTET-STREAM");

                // initialize the http content-disposition header to
                // indicate a file attachment with the default filename
                // "myFile.txt"
                String disHeader = "Attachment;Filename=queryOutput.csv";
                response.setHeader("Content-Disposition", disHeader);

                PrintWriter out = response.getWriter();

                //todo generate linkage format files
                GenotypeToolsManager mgr = new GenotypeToolsManager();
                mgr.writeLinkageFileFromDB(out,snps, generateAnalysisFileForm.getPhenotype(), generateAnalysisFileForm.getCohort(), mgr.getFormats()[Integer.parseInt(generateAnalysisFileForm.getFormat())]);



                response.getWriter().close();
            }catch(Exception e) { // file IO errors
                    e.printStackTrace();
            }

            forward = mapping.findForward("success");
        }
        return forward;
	}
}
